package models.report;

import helpers.ClientRequest;

import java.util.*;

import play.Logger;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import play.data.validation.Constraints.*;
import play.data.format.*;
import play.mvc.Http.Context;
import play.mvc.Http.Request;
import service.Paging;

import javax.persistence.*;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Page;
import com.avaje.ebean.PagingList;
import com.avaje.ebean.Query;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;

@Entity
public class SumUsedCoin extends Model{
	public Integer dateKey;
	
	public String dateValue;
	
	public Integer appId;
	public Integer marketKey;
	public Integer deviceKey;
	
	public Integer buyItemCoin;
	public Integer buySetItemCoin;
	public Integer playGachaCoin;
	public Integer totalCoin;
	
	public static Finder<Long,SumUsedCoin> find = new Finder(
		Long.class, SumUsedCoin.class
	);
	
	public static Paging search(int startTime, int endTime){		
		Request request = Context.current().request();
		
		int pageSize = Integer.parseInt(request.getQueryString("pageSize"));
    	int page = Integer.parseInt(request.getQueryString("page"));
        
    	EbeanServer report = Ebean.getServer("report");
    	
    	String sql = "select date_value, buy_item_coin, buy_setItem_coin as buySetItemCoin, play_gacha_coin, used_coin as totalCoin" 
    		+ " from rpt_sum_sale_daily";  
      
    	if(ClientRequest.getCurrent().marketKey == 0)
    	{
    		sql = " select date_value, SUM(buy_item_coin) as buyItemCoin, SUM(buy_setItem_coin) as buySetItemCoin, SUM(play_gacha_coin) as playGachaCoin, SUM(used_coin) as totalCoin "  
        			+ " from rpt_sum_sale_daily "   
        			+ " group by date_value";  
    	}
    	
    	RawSql rawSql = RawSqlBuilder.parse(sql).create();
            
    	Query<SumUsedCoin> query = report.find(SumUsedCoin.class);
	    query.setRawSql(rawSql);
	    
    	ExpressionList<SumUsedCoin> expression = query.where();
    	
    	if(startTime > 0) expression.ge("date_key", startTime);
    	
    	if(endTime > 0) expression.le("date_key", endTime);
    	
    	expression = helpers.Query.addClientRequestExpression(expression);
    	
    	PagingList<SumUsedCoin> pagingList = expression.findPagingList(pageSize).setFetchAhead(false);
    	
    	Page<SumUsedCoin> page0 = pagingList.getPage(page - 1);
        List<SumUsedCoin> list = page0.getList();
        
    	Paging paging = new Paging(expression.findList().size(), list);
    	
        return paging;
	}
}
